package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.config.CacheService;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.bouncycastle.crypto.modes.kgcm.Tables4kKGCMMultiplier_128;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {


    @Override
    public Long addTask(Task task) {

        //1.把任务存储到数据库中
        boolean success = addTaskToDb(task);

        if (success) {
            //2.把任务存储到redis
            addTaskToCache(task);

        }

        return task.getTaskId();
    }

    @Autowired
    private CacheService cacheService;

    /**
     * 把任务存储到redis
     *
     * @param task
     */
    private void addTaskToCache(Task task) {

        String key = task.getTaskType() + "_" + task.getPriority();

        //获取未来5分钟的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        //2.1 如果任务的执行时间小于等于当前时间，存储list
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= calendar.getTimeInMillis()) {
            //2.2 如果任务的执行时间小于等于预设时间（未来5分钟），存储zset
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }

    }

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    /**
     * 把任务存储到数据库中
     *
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {

        boolean flag = false;

        try {
            //保存任务
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置任务id
            task.setTaskId(taskinfo.getTaskId());

            //保存任务日志
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (BeansException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return flag;

    }

    @Override
    public boolean cancelTask(Long taskId) {

        boolean flag = false;

        //1.删除数据库中的任务，更新任务日志表
        Task task = updateDb(taskId, ScheduleConstants.CANCELLED);

        //2.删除redis中的数据
        if (null != task) {
            removeTaskFromCache(task);
            flag = true;
        }

        return flag;
    }

    /**
     * 删除redis中的数据
     *
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();

        //2.1 如果任务的执行时间小于等于当前时间，存储list
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            //2.2 如果任务的执行时间小于等于预设时间（未来5分钟），存储zset
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除任务，更新日志
     *
     * @param taskId
     * @param status
     */
    private Task updateDb(Long taskId, int status) {

        Task task = null;

        try {
            //删除任务
            taskinfoMapper.deleteById(taskId);
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);


            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
            //更新任务日志
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
        return task;
    }

    @Override
    public Task poll(int taskType, int priority) {

        String key = taskType + "_" + priority;

        Task task = null;

        try {
            //从redis中pop数据
            String taskJson = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (StringUtils.isNotBlank(taskJson)) {
                task = JSON.parseObject(taskJson, Task.class);
                //更新数据库
                updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return task;
    }

    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {

        String key = "FUTURE_SYNC_DATA";
        String token = cacheService.tryLock(key, 1000 * 30);
        if (StringUtils.isNotBlank(token)) {
            log.info("定时刷新执行了,当前时间:{}", new Date());
            //获得未来的所有的key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            if (futureKeys != null && futureKeys.size() > 0) {
                for (String futureKey : futureKeys) {//future_50_100

                    //获取当前的key  topic_50_100
                    String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];

                    //符合条件的数据
                    Set<String> values = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

                    /**
                     * 未来的key,当下的key,符合条件的数据（到期的）
                     */
                    cacheService.refreshWithPipeline(futureKey, topicKey, values);
                }
            }
        }


    }

    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct  //初始化
    public void reloadData(){

        //清理缓存数据
        clear();

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);

        //查询任务小于等于未来5分钟的数据
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().le(Taskinfo::getExecuteTime, calendar.getTime()));
        if(taskinfos != null && taskinfos.size() > 0){
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);
            }
        }

    }

    /**
     * 清理缓存数据
     */
    private void clear() {

        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);

    }
}
